// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const data = [];
  let orderList;
  if(event.status == ""){
    orderList = await findAllOrder(event)
  }else{ 
    orderList = await findAllOrderByStatus(event)
  }
 
  for(let i = 0; i < orderList.list.length; i++){
    let order = {}
      order.title = orderList.list[i].canteen[0].canteen_name + orderList.list[i].window[0].window_name
      order.time = orderList.list[i].order_time
      order.goodsName = orderList.list[i].meal_name
      order.price = orderList.list[i].meal_price
      order.status = orderList.list[i].order_status
      order.num = orderList.list[i].order_random
      order.image = orderList.list[i].meal_img
    data.push(order)
  }
  return data;
}
async function findAllOrder (event){
  return db.collection('order_info').aggregate()
  .match({
    student_id:  event.student_id
  })
  .lookup({
    from: 'window',
    localField: 'window_id',
    foreignField: 'window_id',
    as: 'window'
  })
  .lookup({
    from: 'canteen',
    localField: 'canteen_id',
    foreignField: 'canteen_id',
    as: 'canteen'
  }).end()
  .then()
  .catch()
}
async function findAllOrderByStatus (event){
  return db.collection('order_info').aggregate()
  .match({
    student_id:  event.student_id,
    order_status: event.status
  })
  .lookup({
    from: 'window',
    localField: 'window_id',
    foreignField: 'window_id',
    as: 'window'
  })
  .lookup({
    from: 'canteen',
    localField: 'canteen_id',
    foreignField: 'canteen_id',
    as: 'canteen'
  }).end()
  .then()
  .catch()
}